package com.ruoyi.bpm.utils;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.utils.CollectionUtils;
import com.ruoyi.common.orm.core.page.TableDataInfo;

import java.util.List;
import java.util.function.Consumer;

/**
 * Bean 工具类
 *
 * 1. 默认使用 {@link BeanUtil} 作为实现类，虽然不同 bean 工具的性能有差别，但是对绝大多数同学的项目，不用在意这点性能
 * 2. 针对复杂的对象转换，可以搜参考 AuthConvert 实现，通过 mapstruct + default 配合实现
 *
 * @author 芋道源码
 */
public class BeanUtils {

    public static <T> T toBean(Object source, Class<T> targetClass) {
        return com.ruoyi.common.core.utils.bean.BeanUtils.toBean(source, targetClass);
//        return BeanUtil.toBean(source, targetClass);
    }

    public static <T> T toBean(Object source, Class<T> targetClass, Consumer<T> peek) {
//        T target = toBean(source, targetClass);
//        if (target != null) {
//            peek.accept(target);
//        }
//        return target;
        return com.ruoyi.common.core.utils.bean.BeanUtils.toBean(source, targetClass, peek);
    }

    public static <S, T> List<T> toBean(List<S> source, Class<T> targetType) {
//        if (source == null) {
//            return null;
//        }
//        return CollectionUtils.convertList(source, s -> toBean(s, targetType));
        return com.ruoyi.common.core.utils.bean.BeanUtils.toBean(source, targetType);
    }

    public static <S, T> List<T> toBean(List<S> source, Class<T> targetType, Consumer<T> peek) {
//        List<T> list = toBean(source, targetType);
//        if (list != null) {
//            list.forEach(peek);
//        }
//        return list;
        return com.ruoyi.common.core.utils.bean.BeanUtils.toBean(source, targetType, peek);
    }

    public static <S, T> TableDataInfo<T> toBean(TableDataInfo<S> source, Class<T> targetType) {
        return toBean(source, targetType, null);
    }

    public static <S, T> TableDataInfo<T> toBean(TableDataInfo<S> source, Class<T> targetType, Consumer<T> peek) {
        if (source == null) {
            return null;
        }
        List<T> list = toBean(source.getRows(), targetType);
        if (peek != null) {
            list.forEach(peek);
        }
        return new TableDataInfo<>(list, (int) source.getTotal());
    }

}
